<template>
	<view class="layer">
		<view class="topBox" v-if="!disabled">
			<image class="avatar" :src="userInfo.UserAvatarURL?userInfo.UserAvatarURL:userAUrl"></image>
			<view class="formLable">
				<view style="display: flex;">
					<view class="lableItem">
						{{namePass(userInfo.UserName)||'用户'}}
					</view>
					<view class="lableItem" style="flex: 1;">
						{{phonePass(userInfo.UserPhone)||''}}
					</view>
				</view>
				<view v-if="isFlag == true" class="lableItem" style="display: flex;align-items: center;">
					<image style="width: 40rpx;height: 40rpx;" src="../../static/auth_on.png" mode=""></image>
					<view style="margin-left: 5rpx;font-size: 26rpx;">
						<text style="padding-right: 20rpx;">已认证</text>
						{{userInfo.veriType==0?'(二要素)':userInfo.veriType==1?'(人脸识别签收)':userInfo.veriType==2?'(三要素)':'微信签收'}}
					</view>
				</view>
				<view v-else class="lableItem" style="display: flex;align-items: center;">
					<image style="width: 40rpx;height: 40rpx;" src="../../static/auth_off.png" mode=""></image>
					<view style="margin-left: 5rpx;font-size: 26rpx;">
						请认证身份信息
					</view>
				</view>
			</view>
		</view>
		<view class="topBox" v-else>
			<image class="avatar" :src="userAUrl"></image>
			<view class="formLable">
				<view style="display: flex;">
					<view class="lableItem">
						{{namePass(pObj.FullName) || '测试'}}
					</view>
					<view class="lableItem" style="flex: 1;">
						{{phonePass(pObj.ReceiptPhone) || '测试电话'}}
					</view>
				</view>
				<view class="lableItem">
					{{idCardPass(pObj.IdCard) || ''}}
				</view>
			</view>
		</view>
		<view class="container">
			<view v-for="(item, index) in data" :key="index">
				<view class="info">
					<h3>内容信息</h3>
					<view v-for="(im,ix) in dataHeader" :key="ix">
						<view class="cell" v-if="im.dataIndex!='nums'">
							<text>{{im.title}}</text>
							<b>{{ resetValue(im, item) }}</b>
							<!-- <b>{{ item[im.dataIndex]==null?'':item[im.dataIndex] }}</b> -->
						</view>
					</view>
					<view class="cell"
						style="display: flex;justify-content: flex-end;text-align: right; border-top: 1px dashed #ccc">
						<span style="width: 100px;line-height: 2;">签收量</span>
						<input :disabled="disabled" v-model="item.nums" class="number" type="number" @input="different"
							placeholder="请输入签收量" />
					</view>
				</view>
			</view>
			<view class="info">
				<h3>签收照片</h3>
				<uni-file-picker file-mediatype="image" :del-icon="!disabled" v-model="fileList" :auto-upload="false"
					mode="grid" :sourceType="['camera']" :disabled="disabled" limit="5" @select="afterRead"
					@delete="handleDelete" />
			</view>
			<view class="info" style="border: none">
				<h3>签收人</h3>
				<view class="cell">
					<view v-if="Sign" class="flexCell" @click="handleSignature">
						<img :src="Sign" alt="" class="imgSignature" />
					</view>
					<view v-else @click="handleSignature" style="
			              height: 200px;
			              border: 1px solid #ccc;
			              line-height: 200px;
			              text-align: center;
						  width: 100%;
			            ">
						请签名
					</view>
				</view>
				<view class="positionBox">
					<view class="positionLine">
						{{pObj.SignInAddress?pObj.SignInAddress:'请获取位置信息'}}
					</view>
					<button class="positionBtn" size="mini" type="primary" @click="getPosition" :disabled="disabled">
						<uni-icons color="#fff" type="location" size="30" class="positionIcon"></uni-icons>
					</button>
				</view>
			</view>
		</view>
		<view class="fixedBox">
			<!-- 已签收或拒收 -->
			<view v-if="disabled">
				<view style="display: flex; justify-content: space-between;">
					<button class="submitButton" disabled
						style="width: 270rpx;">{{Status==1?'已签收':Status==2?'已拒收':Status==3?'部分签收':''}}</button>
					<button class="submitButton" @click="toDownload" round type="primary">完成
					</button>
				</view>
			</view>
			<!-- 签收或拒收 -->
			<view v-else
				style="display: flex; justify-content: space-between;align-items: flex-end;box-sizing: border-box;    padding: 0 10px;">
				<button v-if="flag==false" style="opacity: 0.6;width: 100%;" @click="goRealName">请先实名认证</button>
				<button v-if="flag==true"
					:style="{width: '48%',color:'#fff','background-color': difference!=-1?'#e6a23c':'#1aad19'}"
					class="submitButton" @click="handleGenerate(true)">
					{{difference!=-1?'提交差异':'确认'}}
				</button>
				<button v-if="flag==true" style="width: 48%" class="submitButton" type="warn"
					@click="handleGenerate(false)">拒收
				</button>
			</view>



		</view>
		<!-- 确认说明 -->
		<uni-popup ref="remark" type="center" :is-mask-click="false">
			<view class="remarkBox">
				<view class="title">
					请输入{{title}}
				</view>
				<view class="content">
					<textarea class="textarea" :show-confirm-bar="false" :maxlength="1000" v-model="pObj.Memo"
						:placeholder="'请输入' + title">
					</textarea>
					<view class="memoLength">
						{{memoLength}}/1000
					</view>
				</view>
				<view v-if="title!='拒收说明'">
					<view v-for="item in entity.evaluation" :key="item" class="content" style="display: flex;">
						<text style="margin-right: 30rpx;">{{item}}</text>
						<uni-rate v-if="item=='服务'" v-model="entity['service']" />
						<uni-rate v-if="item=='物流'" v-model="entity['logistics']" />
						<uni-rate v-if="item=='产品'" v-model="entity['product']" />
					</view>
				</view>
				<view class="footer">
					<text @click="beforeClose">取消</text>
					<text class="confirmBtn" @click="dialogConfirm">确认</text>
				</view>
			</view>
		</uni-popup>
		<!-- 弹出签字 -->
		<uni-popup ref="popup" background-color="#fff" type="bottom" :is-mask-click="false">
			<Sign ref="sign" :showSign="true" @finish="signFinish" @close="signClose" />
		</uni-popup>
		<!-- 确认说明 -->
		<uni-popup ref="codeBox" type="center" :is-mask-click="false">
			<view class="remarkBox">
				<view class="title">
					请输入验证码
				</view>
				<view class="content">
					<view style="display: flex;">
						<input v-model="code"
							style="border-bottom: 1px solid #ccc;font-size: 20px;height: 28px;flex: 1;" type="number">
						<button size="mini" style="width: 70px;" :disabled="oneMinute<60"
							@click="sendCodeSubmit">{{oneMinute<60?oneMinute+'S':'获取'}}</button>
					</view>
				</view>

				<view class="footer">
					<text @click="codeClose">取消</text>
					<text class="confirmBtn" @click="codeConfirm">确认</text>
				</view>
			</view>
		</uni-popup>
		<!-- 是否已经认证 -->
		<uni-popup ref="mask" type="top" backgroundColor="rgba(0,0,0,0.2)" height="100vh"></uni-popup>
	</view>
</template>

<script>
	import QQMapWX from '../../utils/qqmap-wx-jssdk.min.js'
	import Sign from '@/components/sign.vue'
	import {
		idCardPass,
		namePass,
		phonePass
	} from '@/utils/PrivacyPass.js'
	var qqmapsdk;
	// const NumFormatting = function(data) {
	// 	if (data != null) {
	// 		return Number(data)
	// 			.toFixed(2)
	// 			.replace(/\d{1,3}(?=(\d{3})+(\.\d*)?$)/g, "$&,");
	// 	} else {
	// 		return "";
	// 	}
	// };
	export default {
		components: {
			Sign
		},
		computed: {
			memoLength() {
				return this.pObj.Memo ? this.pObj.Memo.length : 0
			},
		},
		data() {
			return {

				pObj: {

				},
				entity: {},
				data: [],
				digit: "",
				lineWidth: 6,
				lineColor: "#000000",
				bgColor: "#fff",
				resultImg: "",
				isCrop: false,
				time: 10,
				timeShow: false,
				Interval: null,
				fileList: [],
				showPopup: false,
				Sign: "",
				disabled: false, // 控制页面所有操作功能
				title: "",
				Status: "3",
				userAUrl: "https://thirdwx.qlogo.cn/mmopen/vi_32/POgEwh4mIHO4nibH0KlMECNjjGxQUq24ZEaGT4poC6icRiccVGKSyXwibcPq4BWmiaIGuG1icwxaQX6grC9VemZoJ8rg/132",
				userInfo: {},
				userList: [], // 签收人
				timer: null, // 签收码定时器 
				oneMinute: 60, // 签收倒计时
				code: '', // 签收码
				dataHeader: [], // 表格头
				difference: -1,
				address: '',
				checkPhone: false,
				location: {}, // 收货坐标
				nowLocation: {}, // 当前坐标
				CustomerName: '',
				Company: '',
				showCodeBox: false,
				// 上个页面传递过来的当前行数据
				rowData: {},
				// 判断是否实名认证
				flag: false,
				token: '',
				remark: {},
				type: 0,
				realPass: false,
				showPrivacy: true, // 隐私展示
				// 是否认证
				isFlag: false
			}
		},
		onShow() {
			let isFlag = uni.getStorageSync('flag')
			this.isFlag = isFlag
			let obj = uni.getStorageSync('userInfo')
			this.userInfo = typeof obj == 'object' ? obj : {},
				console.log('打印用户信息', this.userInfo)
			if (this.userInfo.sign) this.Sign = this.userInfo.sign // 签名
			this.disabled = false;
			// 判断货单是否已完成
			this.getInfo()
			// let id = uni.getStorageSync('Id')
			// if (!id) {
			// 	uni.redirectTo({
			// 		url: '/pages/index/index'
			// 	})
			// 	uni.showToast({
			// 		icon: 'none',
			// 		title: '获取失败,请重新扫描二维码'
			// 	})
			// 	return;
			// }

		},
		async onLoad(options) {
			let isFlag = uni.getStorageSync('flag')
			this.isFlag = isFlag
			let obj = uni.getStorageSync('userInfo')
			this.userInfo = typeof obj == 'object' ? obj : {},
				// this.rowData = JSON.parse(options.obj)
				console.log('获取传递过来的options', options)
			this.$set(this.rowData, 'Id', options.Id)
			this.$set(this.rowData, 'Company', options.Company)
			// 认证方式签收类别(0二素 1人脸识别签收 2 三要素  3微信签收)
			this.$set(this.rowData, 'SignType', options.SignType)
			// 缓存认证类型
			uni.setStorageSync('type', options.SignType)
			console.log('获取赋值后的rowData', this.rowData)
			uni.showLoading()
			qqmapsdk = new QQMapWX({
				key: '4IIBZ-UJ2CA-C4FKX-C7JLR-WLJY2-WRBPC'
			})
			// // 获取位置信息
			await this.getPosition()
			let id = uni.getStorageSync('Id')

			this.$http('post', '/Base_Manage/Base_Company/GetSignState?Id=' + this.rowData.Company).then(res => {
				if (res.Success) this.showCodeBox = res.Data
			})

			this.getInfo()
			// 获取toekn
			this.getToken()
			// 判断是否实名认证
			this.AuthRealName()
		},

		methods: {
			goRealName() {
				uni.navigateTo({
					url: '/pages/User/RealName?flag=' + this.flag + '&token=' + this.token
				})
			},
			resetValue(val, itemdata) {

				if (itemdata[val.dataIndex]) {
					if (val.type === "text") {
						return itemdata[val.dataIndex];
					} else if (val.type === "number") {
						return this.NumFormatting(
							itemdata[val.dataIndex],
							Number(val.decimals ? val.decimals : 2)
						);
					} else {
						console.log(val)
						console.log(this.NumFormatting(itemdata[val.dataIndex], 2))
						return this.NumFormatting(itemdata[val.dataIndex], 2);
					}
				} else {
					return "";
				}
			},
			NumFormatting(data, num = 2) {

				if (isNaN(Number(data))) {
					return data;
				} else {
					return Number(data).toFixed(num);
				}
			},
			// 获取TOKEN
			async getToken() {
				console.log('获取token', this.userInfo)
				await uni.request({
					url: this.$veriUrl + '/auth/VeriRecord/token?phone=' + this.userInfo.UserPhone,
					method: 'GET'
				}).then(result => {
					let [err, res] = result;
					if (res.data.code == 200) {
						this.token = JSON.parse(res.data.data).access_token
						console.log('获取的token', this.token, this.flag)
					}
				})
			},
			// 验证是否实名认证
			async AuthRealName() {
				console.log('获取实名认证', this.userInfo)
				this.flag = false
				await uni.request({
					url: this.$veriUrl + '/auth/VeriRecord/state?Value=' + this.userInfo.UserPhone,
					method: 'GET'
				}).then(result => {
					let [err, res] = result;
					if (res.data.code == 200) {
						// 说明已认证
						console.log('获取的实名信息=========================', res.data.data, this.token, this.flag,
							this.userInfo)
						this.flag = true
						this.img = res.data.data.veriType
						// 相关字段插入用户信息  从新缓存 
						this.$set(this.userInfo, 'fromDevice', res.data.data.fromDevice)
						this.$set(this.userInfo, 'id', res.data.data.id)
						this.$set(this.userInfo, 'createTime', res.data.data.createTime)
						this.$set(this.userInfo, 'IdCard', res.data.data.idNumber)
						this.$set(this.userInfo, 'RealName', res.data.data.name)
						this.$set(this.userInfo, 'UserName', res.data.data.name)
						this.$set(this.userInfo, 'OpenId', res.data.data.openId)
						this.$set(this.userInfo, 'UserPhone', res.data.data.phone)
						this.$set(this.userInfo, 'remark', res.data.data.remark)
						this.$set(this.userInfo, 'Sign', res.data.data.sign)
						this.$set(this.userInfo, 'state', res.data.data.state)
						this.$set(this.userInfo, 'veriType', res.data.data.veriType)
						// 暂时不删除
						// this.userInfo = {
						// 	...res.data.data,
						// 	name: res.data.data.name || this.userInfo.name,
						// 	phone: res.data.data.phone || this.userInfo.phone,
						// 	idCard: res.data.data.idNumber || this.userInfo.idCard,
						// 	avatarUrl: res.data.data.avatarUrl || this.userInfo.avatarUrl,
						// 	smscode: res.data.data.smscode || this.userInfo.smscode,
						// }
						if (this.userInfo.RealName) this.getBG(this.userInfo.RealName)
						else uni.removeStorageSync('nameBG')
					} else {
						// 说明未认证
						this.flag = false
						this.isAuthentiction()
					}
					console.log('获取鑫缓存suerinfo', this.userInfo)
					uni.removeStorageSync('userInfo')
					// 重新缓存用户信息
					uni.setStorageSync('userInfo', this.userInfo)
					// 存储缓存是否认证
					uni.removeStorageSync('flag', this.flag)
					uni.setStorageSync('flag', this.flag)
				})
				return this.flag
			},
			getBG(name) {
				this.$http('post', '/Base_Manage/Upload/GetNameSign?Name=' + name).then(res => {
					if (res.Success) uni.setStorageSync('nameBG', res.Data)
				})
			},
			// 是否已认证
			isAuthentiction() {
				// this.$refs.mask.open()
				this.showModel('签收对账单需进行实名认证,请前往认证信息进行认证')
			},
			// 提示弹窗
			showModel(title) {
				this.$refs.mask.close()
				uni.hideLoading();
				uni.showModal({
					title: '提示',
					content: title,
					showCancel: false,
					success: (val) => {
						if (val.confirm) {
							uni.navigateTo({
								url: '/pages/User/RealName?flag=' + this.flag + '&token=' + this.token
							})
						}
					}
				})
			},

			getInfo() {
				let id = this.rowData.Id
				this.$http('post', "/BO/BillList/GetBillData", {
					id
				}).then(async (res) => {
					if (res.Success) {
						console.log(res);
						// 重新渲染用户信息  否则渲染不上
						let obj = uni.getStorageSync('userInfo')
						this.userInfo = obj
						// 签收手机号不符打回
						// await this.checkCustomerPhone(res.Data)
						this.pObj = res.Data;
						// 名字
						this.pObj.FullName = this.userInfo.UserName
						// 电话
						this.pObj.ReceiptPhone = this.userInfo.UserPhone
						// 身份证
						this.pObj.IdCard = this.userInfo.IdCard
						// 缓存头像
						this.userAUrl = this.userInfo.UserAvatarURL
						if (!this.pObj.SignInAddress) this.pObj.SignInAddress = this.address
						if (res.Data.Status != 0) {
							this.Status = res.Data.Status
							this.disabled = true;
							if (res.Data.Sign) this.Sign = res.Data.Sign;
							uni.showToast({
								icon: 'none',
								title: '此货单已完成'
							})
						}
						// 是否需要从本地返填手机号
						if (!this.pObj.ReceiptPhone) this.pObj.ReceiptPhone = this.userInfo.phone
						// 货品图片
						if (res.Data.Imgs) {
							this.fileList = res.Data.Imgs.split(',').map(item => ({
								url: item
							}))
						}
						// 签收人图片
						if (res.Data.UserImage) {
							this.userList = [{
								url: res.Data.UserImage
							}]
						} else if (this.userInfo.avatarUrl) {
							this.userList = [{
								url: this.userInfo.avatarUrl
							}]
						}
						// 是否验证签收人手机号
						if (res.Data.IscheckPhone) this.checkPhone = res.Data.IscheckPhone
						if (res.Data.ContactPersonName) this.pObj.FullName = res.Data.ContactPersonName
						uni.setStorageSync("billId", res.Data.BillId)
						if (res.Data.Content) {
							this.entity = JSON.parse(res.Data.Content);
							console.log(this.entity);
							if (this.entity.printlist.length > 0) {
								let arr = []
								this.entity.printlist.filter((item) => {
									if (item.Keys == "table") {
										arr = [item]
									} else if (item.Keys == 'CustomerName') {
										this.CustomerName = item.value
									} else if (item.Keys == 'Company') {
										this.Company = item.value
									}
								});
								if (arr.length > 0) {
									if (this.data.length > 0) return
									this.dataHeader = arr[0].columns
									this.data = arr[0].datalist;
									this.data.forEach(im => im.nums = Number(im.Quantity))
								}
								// 收货坐标 有距离限制再请求
								if (uni.getStorageSync('LType')) {
									let address = this.entity.printlist.filter(item => item.Keys == 'Addres')
									console.log('获取收货地址坐标', address);
									if (address.length > 0) {
										this.getCoordinate(address[0].value)
									}
								}
							} else {
								this.data = [];
							}
						} else {
							uni.showToast({
								icon: 'none',
								title: '暂无信息'
							})
						}
					} else {
						uni.showToast({
							icon: 'none',
							title: '数据获取失败!请刷新页面重试'
						})
					}
				});
			},
			async checkCustomerPhone(e) {
				await this.$http('post', "/BO/CustomerInfo/CustomerIsValid", {
					"id": e.CustomerId
				}).then(result => {
					console.log(result, '222');
					if (result.Data && e.CustomerPhone && e.CustomerPhone != this.userInfo.phone) {
						uni.showModal({
							title: '提示',
							content: '当前手机号与签收人不符,请联系发货方',
							showCancel: false,
							success: (val) => {
								if (val.confirm) {
									uni.reLaunch({
										url: '/pages/index/index'
									})
								}
							}
						})
						return
					}
				})
			},
			// 获取收货地址坐标
			getCoordinate(address) {
				this.$http('post', '/BO/BillList/Getaddress?address=' + address).then(res => {
					if (JSON.parse(res.Data).Success) {
						let obj = JSON.parse(JSON.parse(res.Data).data)
						if (obj.status == 0) {
							this.location = obj.result.location
							console.log(this.location);
						}
					}
				})
			},
			// 隐私加密
			idCardPass(text) {
				return idCardPass(text)
			},
			namePass(text) {
				return namePass(text)
			},
			phonePass(text) {
				return phonePass(text)
			},
			// 差异计算
			different(e) {
				let num = 0;
				let allNum = 0;
				let idx = this.data.findIndex(item => item.nums != item.Quantity)
				this.difference = idx
			},
			// 完善信息
			updateInfo() {
				uni.navigateTo({
					url: '/pages/UpdateInfo/UpdateInfo'
				})
			},
			// 获取签收码
			async sendCodeSubmit() {
				let flag = null
				let BillId = uni.getStorageSync('Id')
				let url = ''
				if (this.checkPhone) url = '/BO/CustomerLinkman/CSSWeChatShort'
				else url = '/BO/CustomerLinkman/CSSendSMS'
				await this.$http('post', url + '?Phone=' + this.userInfo.phone + '&Id=' +
						BillId)
					.then((res) => {
						if (res.Success) {
							clearInterval(this.timer);
							this.timerDisabled = true;
							this.timer = setInterval(() => {
								this.oneMinute--;
								if (this.oneMinute <= 0) {
									clearInterval(this.timer);
									this.oneMinute = 60;
									this.timerDisabled = false;
								}
							}, 1000);
							uni.showToast({
								icon: 'none',
								title: '签收码发送成功'
							})
							flag = true
						} else {
							uni.showModal({
								title: '签收+',
								content: res.Msg,
								showCancel: false
							})
							flag = false
						}
					});
				return flag
			},
			// 位置信息
			async getPosition() {
				let this_ = this
				await uni.getSetting({
					success(res) {
						if (res.authSetting['scope.userLocation']) {
							console.log('123456789')
							// 用户已经授权
							uni.getLocation({
								type: 'wgs84',
								success: (res) => {
									uni.hideLoading()
									console.log('获取坐标uni.getLocation', res)
									this_.nowLocation = {
										lat: res.latitude,
										lng: res.longitude
									}
									qqmapsdk.reverseGeocoder({
										location: {
											latitude: res.latitude,
											longitude: res.longitude
										},
										success: (res) => {
											// console.log("<<<<<" + JSON.stringify(res))
											this_.address = res.result.address
											this_.pObj.SignInAddress = this_.address
										},
										fail: (err) => {
											uni.showToast({
												icon: 'none',
												title: err.errMsg
											})
										}
									})
								},
								fail: (err) => {
									console.log('获取位置信息失败', err)
									uni.hideLoading()
									uni.showToast({
										icon: 'none',
										title: '获取授权信息失败'
									})
								}
							});
						} else {
							// 用户未授权
							uni.showModal({
								title: '提示',
								content: '未授权位置权限，请前往授权',
								success: (val) => {
									uni.openSetting({
										success(res) {
											if (res.authSetting['scope.userLocation']) {

											} else {
												uni.showToast({
													icon: 'none',
													title: '未授权'
												})
											}
										}
									});

								},

							})
						}
					}
				})


			},
			// 图片上传
			afterRead(file) {
				if (!file) return
				console.log(file);
				const fileArr = file.tempFiles.map(item => item.file.path)
				fileArr.forEach(item => {
					uni.compressImage({
						src: item,
						quality: 30,
						success: async result => {
							let res = await uni.uploadFile({
								url: this.$baseUrl +
									'/Base_Manage/Upload/UploadFileProductByForm',
								filePath: item,
								name: 'file'
							});
							if (res.length > 1) {
								let data = JSON.parse(res[1].data)
								this.fileList.push({
									url: data.thumbUrl
								})
								console.log('上传成功后的图片信息', res, this.fileList)
							} else {
								uni.showToast({
									icon: 'none',
									title: '图片上传失败,请重试'
								})
								return false
							}
						}
					})
				})
			},
			handleDelete(e) {
				let index = this.fileList.findIndex(item => item.url == e.tempFilePath)
				this.fileList.splice(index, 1)
			},
			upload() {
				uni.chooseMedia({
					count: 9,
					mediaType: ['image', 'video'],
					sourceType: ['camera'],
					maxDuration: 10,
					camera: 'back',
					success: async (result) => {
						let res = await uni.uploadFile({
							url: this.$baseUrl + '/Base_Manage/Upload/Filleimag',
							filePath: result.tempFiles,
							name: 'file'
						});
						console.log(res);
						if (res.length > 1) {
							let data = JSON.parse(res[1].data)
							this.fileList.push({
								url: data.Data
							})
						} else {
							uni.showToast({
								icon: 'none',
								title: '上传失败,请重试'
							})
							return false
						}
					}
				})

			},
			toDownload() {
				uni.navigateTo({
					url: '/pages/Complete/Complete?Status=' + this.pObj.Status
				})
			},
			// 签字板
			handleSignature() {
				if (this.disabled) return
				this.$refs.popup.open()
			},
			// 预制签名
			signFinish(src) {
				let Sign = uni.getStorageSync('Sign')
				if (src == '1') this.Sign = this.userInfo.sign ? this.userInfo.sign : Sign
				else this.Sign = src;
				this.$refs.popup.close()
			},
			signClose() {
				this.$refs.popup.close()
			},
			// 签收或拒收
			async handleGenerate(bl) {
				this.pObj.Memo = "";
				if (this.data.length <= 0) return uni.showToast({
					icon: 'none',
					title: '请刷新页面重新获取数据'
				});
				// 距离判断
				let nowLocatonNum = uni.getStorageSync('LType')
				if (nowLocatonNum) {
					let locationNum = this.calculateDiscount(this.location.lng, this.location.lat, this.nowLocation
						.lng,
						this.nowLocation.lat)
					if (locationNum > nowLocatonNum) return uni.showToast({
						icon: 'none',
						title: '当前位置距离指定签收位置过远,请到达指定位置进行签收'
					});
				}
				let idx = this.data.findIndex((item) => item.nums < 0);
				if (idx != -1) return uni.showToast({
					icon: 'none',
					title: '请检查签收数量'
				});
				// if (this.fileList.length <= 0) return uni.showToast({
				// 	icon: 'none',
				// 	title: '请拍摄签收照片'
				// })
				if (!this.Sign) return uni.showToast({
					icon: 'none',
					title: '请进行签字确认'
				});
				if (!this.pObj.SignInAddress) return uni.showToast({
					title: '请获取位置信息',
					icon: 'none'
				})
				this.bl = bl
				// 未输入验证码发送
				if (this.showCodeBox && !this.code) {
					this.$refs.codeBox.open()
				} else {
					this.showSubmit()
				}
			},
			// 验证码取消
			codeClose() {
				this.code = ''
				this.$refs.codeBox.close()
			},
			// 验证码确认
			async codeConfirm() {
				let resutl = await this.$http('post', '/BO/BillList/ValidateCode?Id=' + this.pObj.Id + '&SignCode=' +
					this.code)
				if (resutl.Success && resutl.Data) this.showSubmit()
				else uni.showToast({
					icon: 'none',
					title: '验证码错误'
				})
			},
			// 提交
			showSubmit() {
				this.$refs.codeBox.close()
				// 判断是否为点击拒收
				if (!this.bl) {
					this.title = "拒收说明";
					this.$refs.remark.open()
					this.pObj.Status = 2;
					return;
				}
				// 差值
				if (this.difference != -1) {
					this.title = "差异说明";
					this.$refs.remark.open()
					this.pObj.Status = 3;
					let arr = this.data.filter(item => (item.Quantity || 0) - (item.nums || 0) !=
						0)
					let str = arr.map(item => {
						console.log();
						return item.cInvName + ' 差异: ' + ((item.nums || 0) - (item
							.Quantity || 0))
					}).join('；\r\n')
					this.pObj.Memo = str
					return;
				}
				this.title = "确认说明";
				this.$refs.remark.open()
				this.pObj.Status = 1;
				this.pObj.UserImage = this.userList.length > 0 ? this.userList[0].url : ''
			},
			// 收货说明弹窗
			beforeClose() {
				this.$refs.remark.close()
			},
			dialogConfirm() {
				if (this.title != "确认说明" && this.pObj.Memo == "") {
					uni.showToast({
						icon: 'none',
						title: "请填写" + this.title
					})
					return false;
				}
				if (this.entity.evaluation && this.entity.evaluation.length > 0 && this.title != '拒收说明') {
					let flag = false
					this.entity.evaluation.forEach(item => {
						if (item == '服务' && !this.entity['service']) flag = true
						else if (item == '物流' && !this.entity['logistics']) flag = true
						else if (item == '产品' && !this.entity['product']) flag = true
					})
					if (flag) return uni.showToast({
						icon: 'none',
						title: '请进行星级评分'
					})
				}
				this.$refs.remark.close()
				this.submit();
			},
			// 保存
			async submit() {
				uni.showLoading()
				if (this.title == '拒收说明') this.data.forEach(item => item.nums = 0)
				this.pObj.Imgs = this.fileList.map((item) => item.url).join(",");
				// 表格
				let idx = this.entity.printlist.findIndex((item) => item.Keys == "table");
				this.entity.printlist[idx].datalist = this.data;
				// 备注
				let idx2 = this.entity.printlist.findIndex((item) => item.Keys == "Memo");
				if (idx2 !== -1) this.entity.printlist[idx2].value = this.pObj.Memo
				// 签收地址
				let idx3 = this.entity.printlist.findIndex((item) => item.Keys == "SignInAddress");
				if (idx3 !== -1) this.entity.printlist[idx3].value = this.pObj.SignInAddress
				this.pObj.Sign = this.Sign; // 签名
				this.pObj.FullName = this.userInfo.name // 签收人名称
				this.pObj.ReceiptPhone = this.userInfo.phone // 签收人手机号
				this.pObj.IdCard = this.userInfo.idCard // 签收人身份证号
				this.pObj.Content = JSON.stringify(this.entity); // JSON
				this.pObj.IP = uni.getStorageSync('DeviceId') // 设备id
				this.pObj.DeviceName = uni.getStorageSync('DeviceName') // 手机型号
				console.log('最终传递的所有参数信息是', this.pObj, this.fileList)
				uni.setStorageSync('Sign', this.Sign) // 签字 本地缓存
				await this.$http('post', "/BO/BillList/SaveSignData", this.pObj).then(async (res) => {
					if (res.Success) {
						uni.showToast({
							icon: 'none',
							title: '操作成功!'
						})
						// if (this.title == '确认说明' && this.pObj.IsEvidence) await this.toChain()
						uni.navigateTo({
							url: '/pages/Complete/Complete?Status=' + this.pObj.Status
						})
					} else {
						uni.showToast({
							icon: 'none',
							title: res.Msg
						})
					}
					uni.hideLoading()
				});
				await this.$http('post', '/BO/BillList/GetOpenIdList?Id=' + this.pObj.Id).then(async res => {
					if (res.Success) {
						// token获取
						let result = await this.$http('GET', '/Base_Manage/Home/GetWxAccessTokenNoCode')
						let access_token = JSON.parse(result.Data).access_token
						res.Data.forEach(item => {
							this.publicPush(access_token, item)
						})
					}
				})
			},
			// 上链
			async toChain() {
				let result = await this.$chttp('GET', '/Chain/auth?id=' + this.userInfo.phone)
				console.log(result);
				if (result.Success) uni.setStorageSync('token', 'Bearer ' + result.Data)
				else return
				this.$chttp('POST', '/Chain', {
					"shipperId": this.pObj.Company,
					"billId": this.pObj.Id,
					"body": JSON.stringify(this.pObj),
					"name": '回执单号:' + this.pObj.BillId,
					description: `${this.userInfo.name} ${this.userInfo.phone}对回执单${this.pObj.BillId}签收了`,
					cCusName: this.pObj.Customer || ''
				}).then(res => {
					console.log(res);
				})
			},
			// 公众号推送
			async publicPush(access_token, id) {
				this.$http('POST', '/Base_Manage/Home/PutWxMessage', {
					"AccessToken": access_token,
					JsonStr: JSON.stringify({
						touser: id,
						template_id: 'N83E6yjj2O2PavcmDgR3POlCLZfo3jDd8CAWBzZyx1s',
						url: 'https://hzq.yoojet.com/#/SendSMSMobile?id=' + this.pObj.Id,
						data: {
							'thing2': {
								value: this.pObj.CompayName,
								"color": "#173177"
							},
							'thing3': {
								value: this.pObj.Customer,
								"color": "#173177"
							},
							'time4': {
								value: this.pObj.CreateTime.substring(0, 10),
								"color": "#173177"
							},
							'time5': {
								value: this.getNowDate(),
								"color": "#173177"
							},
							'thing6': {
								value: this.userInfo.name,
								"color": "#173177"
							}
						}
					})
				}).then(res => {
					console.log(res);
				})

				// uni.request({
				// 	url: 'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=' +
				// 		access_token,
				// 	method: 'POST',
				// 	data: {
				// 		touser: id,
				// 		template_id: 'N83E6yjj2O2PavcmDgR3POlCLZfo3jDd8CAWBzZyx1s',
				// 		url: 'https://hzq.yoojet.com/#/SendSMSMobile?id=' + this.pObj.Id,
				// 		data: {
				// 			'thing2': {
				// 				value: this.Company,
				// 				"color": "#173177"
				// 			},
				// 			'thing3': {
				// 				value: this.CustomerName,
				// 				"color": "#173177"
				// 			},
				// 			'time4': {
				// 				value: this.pObj.CreateTime.substring(0, 10),
				// 				"color": "#173177"
				// 			},
				// 			'time5': {
				// 				value: this.getNowDate(),
				// 				"color": "#173177"
				// 			},
				// 			'thing6': {
				// 				value: this.userInfo.name,
				// 				"color": "#173177"
				// 			}
				// 		}
				// 	}
				// }).then(res => {
				// 	console.log(res);
				// })
			},
			// 计算坐标距离
			calculateDiscount(lng1, lat1, lng2, lat2) {
				const radLat1 = (lat1 * Math.PI) / 180.0;
				const radLat2 = (lat2 * Math.PI) / 180.0;
				const a = radLat1 - radLat2;
				const b = (lng1 * Math.PI) / 180.0 - (lng2 * Math.PI) / 180.0;
				let s =
					2 *
					Math.asin(
						Math.sqrt(
							Math.pow(Math.sin(a / 2), 2) +
							Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)
						)
					);
				s = s * 6378.137; // EARTH_RADIUS;
				s = Math.round(s * 10000) / 10000;
				s = s * 1000;
				if (isNaN(s)) {
					return 0;
				}
				s = Math.floor((s / 1000) * 100) / 100;
				// 小于1000米直接返回
				return s.toFixed(2);
			},
			// 日期
			getNowDate() {
				var date = new Date();
				var sign2 = ":";
				var year = date.getFullYear() // 年
				var month = date.getMonth() + 1; // 月
				var day = date.getDate(); // 日
				if (month >= 1 && month <= 9) {
					month = "0" + month;
				}
				if (day >= 0 && day <= 9) {
					day = "0" + day;
				}
				return year + "-" + month + "-" + day
			}
		}
	}
</script>

<style scoped lang="scss">
	.positionBox {
		display: flex;
		align-items: center;
		margin-top: 20px;
		height: 40px;

		.positionLine {
			flex: 1;
			height: 100%;
			overflow-y: scroll;
			box-sizing: border-box;
			border-bottom: 1px solid #ccc;
		}

		.positionBtn {
			height: 100%;
			background: linear-gradient(to bottom, #5cccfe, #2799f9);
			border: none;

			.positionIcon {
				line-height: 40px;
				color: #fff;
			}
		}
	}

	.avatar {
		width: 70px;
		height: 70px;
	}

	.topBox {
		height: 72px;
		overflow: hidden;
		box-sizing: border-box;
		display: flex;
		position: relative;
		align-items: center;
	}

	.formLable {
		display: flex;
		flex-direction: column;
		padding: 0 20rpx;
		flex: 1;

		.lableItem {
			height: 35px;
			line-height: 35px;
			margin-right: 10px;
			color: #000;
		}
	}

	.fixedBox {
		position: fixed;
		bottom: 0;
		left: 0;
		width: 100vw;
		background-color: #fff;
		padding-bottom: 30px;
		z-index: 9;
	}

	.remarkBox {
		width: 80vw;
		border-radius: 10px;
		background-color: #fff;
		box-sizing: border-box;

		.title {
			text-align: center;
			line-height: 4;
			color: #666;
		}

		.content {
			padding: 10px;
			padding-top: 0;

			.textarea {
				border: 1px solid #b7b7b7;
				width: 100%;
				border-radius: 3px;
				padding: 5px;
				box-sizing: border-box;
			}

			.memoLength {
				text-align: right;
				color: #666;
			}
		}

		.footer {
			display: flex;
			border-top: 1px solid #f0f0f0;

			text {
				line-height: 3;
				text-align: center;
				flex: 1;
			}

			.confirmBtn {
				color: #007aff;
				border-left: 1px solid #f0f0f0;
			}
		}
	}

	.container {
		box-sizing: border-box;
		padding: 0 10px;
		box-shadow: 0 2px 10px #ccc;
		border-radius: 20px;
		width: 94%;
		margin: 0 auto;
		background: #fff;
	}

	.logoTitlelit {
		margin: 0;
		margin-bottom: 6vh;
		text-align: center;
		color: #fff;
		font-size: 20px;
		font-weight: bold;
	}

	.flexCell {
		display: flex;
		align-items: center;
		justify-content: center;
		height: 180px;
		overflow: hidden;
		width: 100%;
	}

	.imgSignature {
		transform: rotate(-90deg);
		width: 160px;
	}

	b {
		font-weight: normal;
		color: #777;
	}

	.layer {
		padding: 20px 10px;
		min-height: calc(100vh - 44px);
		padding-bottom: 90px;
		box-sizing: border-box;
	}

	h3 {
		margin: 0px 0;
	}

	.info {
		padding: 5px;
		line-height: 1.4;
		/* background: #fff; */
		margin: 10px 0;
		border-bottom: 1px solid #ccc;
		font-size: 12px;
	}

	.info .cell {
		color: #000;
		display: flex;

		text {
			min-width: 61px;
		}

		b {
			margin-left: 10px;
		}
	}

	.info .number {
		margin-left: 5px;
		border-radius: none;
		width: 120px;
		border: none;
		border-bottom: 1px solid #666;
		height: 22px;
		text-align: left;
	}

	.logo {
		width: 100%;
		height: 10vh;
		display: flex;
		align-items: flex-end;
		justify-content: center;
	}

	.logo img {
		width: 50px;
	}

	.logo .logoTitle {
		color: #fff;
		margin: 0;
		margin-bottom: 10px;
		font-weight: bold;
		font-size: 32px;
	}

	.van-button-css {
		border-radius: 10px;
		height: 36px;
		line-height: 36px;
	}

	.submitButton {
		margin: 0 auto;
		margin-top: 10px;
		width: 90vw;
		display: block;
		border-radius: 5px;
	}
</style>